package dao

import javax.inject.Inject
import models.Tables._
import play.api.db.slick.{DatabaseConfigProvider, HasDatabaseConfigProvider}
import slick.jdbc.JdbcProfile

import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global

/**
 * Created by yz on 2018/5/29
 */
class FileDataDao @Inject()(protected val dbConfigProvider: DatabaseConfigProvider) extends
  HasDatabaseConfigProvider[JdbcProfile] {

  import utils.MyPostgresProfile.api._

  def insert(row: FileDataRow): Future[Unit] = db.run(FileData += row).map(_ => ())

  def selectAllFileName(userId: Int, kind: String) = db.run(FileData.
    filter(x => x.userId === userId).filter(_.kind === kind).map(_.fileName).result.map(_.toList))

  def selectAll(userId: Int, kind: String) = db.run(FileData.
    filter(x => x.userId === userId).filter(_.kind === kind).sortBy(_.id.desc).result)

  def select(id: Int) = db.run(FileData.
    filter(x => x.id === id).result.head)

  def selectAll(ids: List[Int]) = db.run(FileData.
    filter(x => x.id.inSetBind(ids)).result)

  def select(userId: Int, fileName: String, kind: String) = db.run(FileData.
    filter(x => x.userId === userId).filter(_.fileName === fileName).filter(_.kind === kind).result.head)

  def delete(userId: Int, id: Int): Future[Unit] = db.run(FileData.filter(_.userId === userId).filter(_.id === id).
    delete).map(_ => ())

  def deletes(userId: Int, ids: List[Int]): Future[Unit] = db.run(FileData.filter(_.userId === userId).
    filter(_.id.inSetBind(ids)).delete).map(_ => ())

  def update(row: FileDataRow): Future[Unit] = db.run(FileData.filter(_.id === row.id).update(row)).
    map(_ => ())

}
